package com.jsh.erp.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jsh.erp.constants.BusinessConstants;
import com.jsh.erp.datasource.entities.*;
import com.jsh.erp.datasource.mappers.*;
import com.jsh.erp.service.depot.DepotService;
import com.jsh.erp.service.material.MaterialService;
import com.jsh.erp.service.report.ReportMaterialInventoryDailyService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;

@RestController
@RequestMapping(value = "/finance-report")
@Api(tags = {"财务报表"})
public class FinanceReportController {
    @Autowired private ReportMaterialInventoryDailyService reportMaterialInventoryDailyService;
    @Autowired private ReportMaterialInventoryDailyMapper reportMaterialInventoryDailyMapper;
    @Autowired private MaterialMapper materialMapper;
    @Autowired private MaterialService materialService;
    @Autowired private DepotService depotService;

    @GetMapping("/daily-report")
    public JSONObject dailyReport(String reportDate, String depotId) throws Exception {
        Depot depot = depotService.getDepot(Long.parseLong(depotId));
        ReportMaterialInventoryDailyExample example = new ReportMaterialInventoryDailyExample();
        example.createCriteria().andReportDateEqualTo(reportDate).andDepotIdEqualTo(depotId);
        List<ReportMaterialInventoryDaily> dailyList = reportMaterialInventoryDailyMapper.selectByExampleWithBLOBs(example);

        if (dailyList.isEmpty()){
            return new JSONObject().fluentPut("code",200).fluentPut("data",new JSONObject().fluentPut("rows",new JSONArray()));
        }else{
            ReportMaterialInventoryDaily dailyReport = dailyList.get(0);
            JSONObject reportItem = new JSONObject();
            reportItem.put("reportDate", dailyReport.getReportDate());
            reportItem.put("depotId", dailyReport.getDepotId());
            reportItem.put("depotName", depot.getName());
            JSONArray materialPriceCounts = JSONArray.parseArray(dailyReport.getContent());
            BigDecimal materialTotal = new BigDecimal(0);
            JSONArray priceItemArray = new JSONArray();
            for (int i = 0; i < materialPriceCounts.size(); i++) {
                JSONObject materialStockInfo = materialPriceCounts.getJSONObject(i);
                Material material = materialService.getMaterial(materialStockInfo.getLong("id"));
                JSONArray priceCounts = materialStockInfo.getJSONArray("priceCounts");

                for (int j = 0; j < priceCounts.size(); j++) {
                    if ( priceCounts.getJSONObject(j).getString("depotId").equals(depotId)){
                        JSONObject priceCount = priceCounts.getJSONObject(j).getJSONObject("priceCount");
                        for (String price : priceCount.keySet()){
                            BigDecimal priceDecimal = new BigDecimal(price);
                            BigDecimal subTotalDecimal = priceDecimal.multiply(new BigDecimal(priceCount.getString(price)));
                            JSONObject priceItemJson = new JSONObject();
                            priceItemJson.put("price", priceDecimal.setScale(2, RoundingMode.HALF_UP));
                            priceItemJson.put("count", priceCount.getString(price));
                            priceItemJson.put("subTotal", subTotalDecimal.setScale(2, RoundingMode.HALF_UP));
                            priceItemJson.put("material", material);
                            priceItemJson.put("materialFullBarCode",  materialStockInfo.getString("fullBarCode"));
                            priceItemJson.put("currentStockPrice",  materialStockInfo.getString("currentStockPrice"));
                            priceItemJson.put("currentStock",  materialStockInfo.getString("currentStock"));
                            priceItemJson.put("initialStock",  materialStockInfo.getString("initialStock"));
                            priceItemJson.put("purchaseDecimal",  materialStockInfo.getString("purchaseDecimal"));
                            priceItemArray.add(priceItemJson);
                            materialTotal = materialTotal.add(subTotalDecimal);
                        }
                    }
                }


            }
            reportItem.put("materialPriceCounts", materialPriceCounts);
            return new JSONObject().fluentPut("code",200)
                    .fluentPut("data",new JSONObject().fluentPut("rows", priceItemArray).fluentPut("total",priceItemArray.size()));
        }
    }

    @PostMapping("/last")
    public JSONObject getCurrentDateReport(){
        MaterialExample example = new MaterialExample();
        example.createCriteria().andDeleteFlagEqualTo(BusinessConstants.DELETE_FLAG_EXISTS);
        List<Material> materials = materialMapper.selectByExample(example);
        JSONArray results = new JSONArray();
        for (Material material : materials){
            JSONObject result = reportMaterialInventoryDailyService.getMaterialDetails(material.getId());
            if (!result.getJSONArray("priceCount").isEmpty()) {
                results.add(new JSONObject().fluentPut("materialId", material.getId()).fluentPut("material", material).fluentPut("priceCount", result.getJSONArray("priceCount")));
            }
        }
        return new JSONObject().fluentPut("data",results);
    }

    @PostMapping("/materialId")
    public JSONObject getDateReport(@RequestBody JSONObject requestParams){
        Long materialId = requestParams.getLong("materialId");
        JSONObject materialDetails = reportMaterialInventoryDailyService.getMaterialDetails(materialId);
        JSONArray logs = materialDetails.getJSONArray("logs");
        JSONArray resultLogs = new JSONArray();
        for (int i = 0; i < logs.size(); i++) {
            String logsString = logs.getString(i);
            String logTime = logsString.split(",")[0];
            String logType = logsString.split(",")[1];
            String logContent = logsString.substring(logsString.indexOf(logType)+1);
            resultLogs.add(new JSONObject().fluentPut("logTime",logTime).fluentPut("logType",logType).fluentPut("logContent",logContent));
        }
        materialDetails.remove("logs");
        return new JSONObject().fluentPut("code",200).fluentPut("data",new JSONObject().fluentPut("materialDetails", materialDetails).fluentPut("logs",resultLogs));
    }
}
